package com.aaa.sbm.service.impl;

import com.aaa.sbm.dao.CategoryDao;
import com.aaa.sbm.entity.Category;
import com.aaa.sbm.service.CategoryService;
import com.aaa.sbm.util.Result;
import com.aaa.sbm.common.ResultUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    
    @Resource
    private CategoryDao categoryDao;
    
    @Override
    @Transactional
    public Result addCategory(Category category) {
        // 检查类别编码是否已存在
        Category existCategory = categoryDao.selectByCode(category.getCategoryCode());
        if (existCategory != null) {
            return ResultUtil.fail("类别编码已存在");
        }
        
        // 检查类别名称是否已存在
        existCategory = categoryDao.selectByName(category.getCategoryName());
        if (existCategory != null) {
            return ResultUtil.fail("类别名称已存在");
        }
        
        int rows = categoryDao.insert(category);
        return rows > 0 ? ResultUtil.success("添加成功") : ResultUtil.fail("添加失败");
    }
    
    @Override
    @Transactional
    public Result updateCategory(Category category) {
        // 检查类别是否存在
        Category existCategory = categoryDao.selectById(category.getId());
        if (existCategory == null) {
            return ResultUtil.fail("类别不存在");
        }
        
        // 如果修改了类别名称，需要检查新名称是否已存在
        if (!existCategory.getCategoryName().equals(category.getCategoryName())) {
            Category nameExist = categoryDao.selectByName(category.getCategoryName());
            if (nameExist != null) {
                return ResultUtil.fail("类别名称已存在");
            }
        }
        
        int rows = categoryDao.update(category);
        return rows > 0 ? ResultUtil.success("更新成功") : ResultUtil.fail("更新失败");
    }
    
    @Override
    @Transactional
    public Result deleteCategory(Long id) {
        // 检查类别是否存在
        Category category = categoryDao.selectById(id);
        if (category == null) {
            return ResultUtil.fail("类别不存在");
        }
        
        // TODO: 检查是否有商品使用此类别
        
        int rows = categoryDao.deleteById(id);
        return rows > 0 ? ResultUtil.success("删除成功") : ResultUtil.fail("删除失败");
    }
    
    @Override
    public Result getCategory(Long id) {
        Category category = categoryDao.selectById(id);
        if (category == null) {
            return ResultUtil.fail("类别不存在");
        }
        return ResultUtil.success(category);
    }
    
    @Override
    public Result getAllCategories() {
        List<Category> categories = categoryDao.selectAll();
        return ResultUtil.success(categories);
    }
} 